<template>
  <div class="certification-form-layout">
    <!-- 左侧导航栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <div class="logo">
          <img src="/666.png" alt="Logo" />
        </div>
        <div class="logo-text">{{ $t('enterpriseCertificationForm.logoText') }}</div>
      </div>
      
      <div class="sidebar-menu">
        <div 
          class="menu-item" 
          :class="{ active: currentRoute === 'enterprise-certification' }"
          @click="navigateTo('enterprise-certification')"
        >
          <span class="menu-text">{{ $t('enterpriseCertificationForm.enterpriseCertification') }}</span>
          <div class="menu-icon">
            <el-icon size="16"><ArrowUp /></el-icon>
            <el-icon size="16"><ArrowDown /></el-icon>
          </div>
        </div>
        <div 
          class="menu-item" 
          @click="goBack"
        >
          <span class="menu-text">{{ $t('enterpriseCertificationForm.back') }}</span>
          <div class="menu-icon">←</div>
        </div>
        <div 
          class="menu-item" 
          :class="{ active: currentRoute === 'enterprise-post' }"
          @click="navigateTo('enterprise-post')"
        >
          <span class="menu-text">{{ $t('enterpriseCertificationForm.createDemand') }}</span>
          <div class="menu-icon">📄</div>
        </div>
        <div 
          class="menu-item" 
          :class="{ active: currentRoute === 'enterprise-applications' }"
          @click="navigateTo('enterprise-applications')"
        >
          <span class="menu-text">{{ $t('enterpriseCertificationForm.applicationRecords') }}</span>
          <div class="menu-icon">📄</div>
        </div>
      </div>
    </div>

    <!-- 右侧主内容区 -->
    <div class="main-content">
      <div class="certification-form-container">
        <div class="form-header">
          <h1 class="page-title">{{ $t('enterpriseCertificationForm.pageTitle') }}</h1>
          <p class="page-subtitle">{{ $t('enterpriseCertificationForm.pageSubtitle') }}</p>
        </div>

        <el-card class="certification-form-card">
          <el-form 
            ref="certificationFormRef"
            :model="certificationForm"
            :rules="certificationRules"
            label-width="120px"
            class="certification-form"
          >
            <!-- 基本信息 -->
            <div class="form-section">
              <h3 class="section-title">{{ $t('enterpriseCertificationForm.basicInfo') }}</h3>
              <div class="form-row">
                <div class="form-column">
                  <el-form-item :label="$t('enterpriseCertificationForm.companyName')" prop="companyName">
                    <el-input v-model="certificationForm.companyName" :placeholder="$t('enterpriseCertificationForm.enterCompanyName')"></el-input>
                  </el-form-item>
                </div>
                <div class="form-column">
                  <el-form-item :label="$t('enterpriseCertificationForm.creditCode')" prop="creditCode">
                    <el-input v-model="certificationForm.creditCode" :placeholder="$t('enterpriseCertificationForm.enterCreditCode')"></el-input>
                  </el-form-item>
                </div>
              </div>
              <div class="form-row">
                <div class="form-column">
                  <el-form-item :label="$t('enterpriseCertificationForm.businessLicense')" prop="businessLicense">
                    <div class="upload-container">
                      <el-upload
                        ref="licenseUploadRef"
                        :action="uploadAction"
                        :headers="uploadHeaders"
                        :on-change="handleLicenseChange"
                        :on-error="onUploadError"
                        :auto-upload="false"
                        :show-file-list="false"
                        accept=".jpg,.jpeg,.png,.pdf"
                        class="upload-component"
                      >
                        <div class="upload-area" v-if="!certificationForm.businessLicense.length">
                          <el-icon size="24" color="#409EFF"><Upload /></el-icon>
                          <div class="upload-text">{{ $t('enterpriseCertificationForm.clickToUploadLicense') }}</div>
                          <div class="upload-hint">{{ $t('enterpriseCertificationForm.uploadLicenseHint') }}</div>
                        </div>
                        <div class="upload-preview" v-else>
                          <div class="preview-content">
                            <el-icon size="32" color="#67C23A"><CircleCheckFilled /></el-icon>
                            <div class="preview-text">{{ certificationForm.businessLicense[0].name }}</div>
                            <div class="preview-hint">{{ $t('enterpriseCertificationForm.licenseSelected') }}</div>
                          </div>
                          <el-button 
                            type="danger" 
                            size="small" 
                            @click="removeBusinessLicense"
                            class="remove-btn"
                          >
                            {{ $t('enterpriseCertificationForm.reupload') }}
                          </el-button>
                        </div>
                      </el-upload>
                    </div>
                  </el-form-item>
                </div>
                <div class="form-column">
                  <el-form-item :label="$t('enterpriseCertificationForm.companyLogo')" prop="companyLogo">
                    <div class="upload-container">
                      <el-upload
                        ref="logoUploadRef"
                        :action="uploadAction"
                        :headers="uploadHeaders"
                        :on-change="handleLogoChange"
                        :on-error="onUploadError"
                        :auto-upload="false"
                        :show-file-list="false"
                        accept=".jpg,.jpeg,.png"
                        class="upload-component"
                      >
                        <div class="upload-area" v-if="!certificationForm.companyLogo.length">
                          <el-icon size="24" color="#409EFF"><Upload /></el-icon>
                          <div class="upload-text">{{ $t('enterpriseCertificationForm.clickToUploadLogo') }}</div>
                          <div class="upload-hint">{{ $t('enterpriseCertificationForm.uploadLogoHint') }}</div>
                        </div>
                        <div class="upload-preview" v-else>
                          <div class="preview-content">
                            <el-icon size="32" color="#67C23A"><CircleCheckFilled /></el-icon>
                            <div class="preview-text">{{ certificationForm.companyLogo[0].name }}</div>
                            <div class="preview-hint">{{ $t('enterpriseCertificationForm.logoSelected') }}</div>
                          </div>
                          <el-button 
                            type="danger" 
                            size="small" 
                            @click="removeCompanyLogo"
                            class="remove-btn"
                          >
                            {{ $t('enterpriseCertificationForm.reupload') }}
                          </el-button>
                        </div>
                      </el-upload>
                    </div>
                  </el-form-item>
                </div>
              </div>
            </div>

            <!-- 联系信息 -->
            <div class="form-section">
              <h3 class="section-title">{{ $t('enterpriseCertificationForm.contactInfo') }}</h3>
              <div class="form-row">
                <div class="form-column">
                  <el-form-item :label="$t('enterpriseCertificationForm.operatorName')" prop="operatorName">
                    <el-input v-model="certificationForm.operatorName" :placeholder="$t('enterpriseCertificationForm.enterOperatorName')"></el-input>
                  </el-form-item>
                </div>
                <div class="form-column">
                  <el-form-item :label="$t('enterpriseCertificationForm.operatorPosition')" prop="operatorPosition">
                    <el-input v-model="certificationForm.operatorPosition" :placeholder="$t('enterpriseCertificationForm.enterOperatorPosition')"></el-input>
                  </el-form-item>
                </div>
              </div>
              <div class="form-row">
                <div class="form-column">
                  <el-form-item :label="$t('enterpriseCertificationForm.phone')" prop="phone">
                    <el-input v-model="certificationForm.phone" :placeholder="$t('enterpriseCertificationForm.enterPhone')"></el-input>
                  </el-form-item>
                </div>
                <div class="form-column">
                  <el-form-item :label="$t('enterpriseCertificationForm.email')" prop="email">
                    <el-input v-model="certificationForm.email" :placeholder="$t('enterpriseCertificationForm.enterEmail')"></el-input>
                  </el-form-item>
                </div>
              </div>
            </div>

            <!-- 公司信息 -->
            <div class="form-section">
              <h3 class="section-title">{{ $t('enterpriseCertificationForm.companyInfo') }}</h3>
              <div class="form-row">
                <div class="form-column">
                  <el-form-item :label="$t('enterpriseCertificationForm.companyDescription')" prop="companyDescription">
                    <el-input 
                      v-model="certificationForm.companyDescription" 
                      type="textarea" 
                      :rows="4"
                      :placeholder="$t('enterpriseCertificationForm.enterCompanyDescription')"
                    ></el-input>
                  </el-form-item>
                </div>
                <div class="form-column">
                  <el-form-item :label="$t('enterpriseCertificationForm.mainBusiness')" prop="mainBusiness">
                    <el-select 
                      v-model="certificationForm.mainBusiness" 
                      multiple 
                      :placeholder="$t('enterpriseCertificationForm.selectMainBusiness')"
                      style="width: 100%"
                    >
                      <el-option 
                        v-for="option in businessOptions" 
                        :key="option.value" 
                        :label="option.label" 
                        :value="option.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
              <div class="form-row">
                <div class="form-column">
                  <el-form-item :label="$t('enterpriseCertificationForm.website')" prop="website">
                    <el-input v-model="certificationForm.website" :placeholder="$t('enterpriseCertificationForm.enterWebsite')"></el-input>
                  </el-form-item>
                </div>
                <div class="form-column">
                  <el-form-item :label="$t('enterpriseCertificationForm.industry')" prop="industry">
                    <el-select v-model="certificationForm.industry" :placeholder="$t('enterpriseCertificationForm.selectIndustry')" style="width: 100%">
                      <el-option 
                        v-for="option in industryOptions" 
                        :key="option.value" 
                        :label="option.label" 
                        :value="option.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
              <div class="form-row">
                <div class="form-column">
                  <el-form-item :label="$t('enterpriseCertificationForm.companySize')" prop="companySize">
                    <el-select v-model="certificationForm.companySize" :placeholder="$t('enterpriseCertificationForm.selectCompanySize')" style="width: 100%">
                      <el-option 
                        v-for="option in companySizeOptions" 
                        :key="option.value" 
                        :label="option.label" 
                        :value="option.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div class="form-column">
                  <!-- 预留空间 -->
                </div>
              </div>
            </div>

            <!-- 表单操作 -->
            <div class="form-actions">
              <el-button @click="resetForm">{{ $t('enterpriseCertificationForm.reset') }}</el-button>
              <el-button type="primary" @click="submitCertification" :loading="submitting">
                {{ submitting ? $t('enterpriseCertificationForm.submitting') : $t('enterpriseCertificationForm.submit') }}
              </el-button>
            </div>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  CircleCheckFilled, 
  Clock, 
  Warning,
  Document,
  Check,
  InfoFilled,
  Search,
  User,
  Lightning,
  Setting,
  ArrowUp,
  ArrowDown,
  Upload
} from '@element-plus/icons-vue'
import { userApi } from '../../api'
import { certificationManager } from '../../utils/certification'
import { useI18n } from 'vue-i18n'

const { t, locale } = useI18n()

// 语言检测逻辑
const detectLanguage = () => {
  const savedLang = localStorage.getItem('lang')
  if (savedLang && (savedLang === 'zh' || savedLang === 'en')) {
    locale.value = savedLang
  } else {
    // 如果没有保存的语言设置，默认使用中文
    locale.value = 'zh'
    localStorage.setItem('lang', 'zh')
  }
}

const router = useRouter()
const route = useRoute()

// 响应式数据
const certificationFormRef = ref()
const licenseUploadRef = ref()
const logoUploadRef = ref()
const submitting = ref(false)

// 认证表单数据
const certificationForm = reactive({
  companyName: '',
  creditCode: '',
  businessLicense: [],
  operatorName: '',
  operatorPosition: '',
  phone: '',
  email: '',
  companyLogo: [],
  companyDescription: '',
  mainBusiness: [],
  website: '',
  industry: '',
  companySize: ''
})

// 表单验证规则 - 使用国际化文本
const certificationRules = computed(() => ({
  companyName: [
    { required: true, message: t('enterpriseCertificationForm.companyNameRequired'), trigger: 'blur' },
    { min: 2, max: 100, message: t('enterpriseCertificationForm.companyNameLength'), trigger: 'blur' }
  ],
  creditCode: [
    { required: true, message: t('enterpriseCertificationForm.creditCodeRequired'), trigger: 'blur' },
    { pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/, message: t('enterpriseCertificationForm.creditCodeInvalid'), trigger: 'blur' }
  ],
  businessLicense: [
    { required: true, message: t('enterpriseCertificationForm.businessLicenseRequired'), trigger: 'change' },
    { type: 'array', min: 1, message: t('enterpriseCertificationForm.businessLicenseRequired'), trigger: 'change' },
    { validator: (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error(t('enterpriseCertificationForm.businessLicenseRequired')))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
  operatorName: [
    { required: true, message: t('enterpriseCertificationForm.operatorNameRequired'), trigger: 'blur' }
  ],
  operatorPosition: [
    { required: true, message: t('enterpriseCertificationForm.operatorPositionRequired'), trigger: 'blur' }
  ],
  phone: [
    { required: true, message: t('enterpriseCertificationForm.phoneRequired'), trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: t('enterpriseCertificationForm.phoneInvalid'), trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: t('enterpriseCertificationForm.emailInvalid'), trigger: 'blur' }
  ],
  companyLogo: [
    { required: true, message: t('enterpriseCertificationForm.companyLogoRequired'), trigger: 'change' },
    { type: 'array', min: 1, message: t('enterpriseCertificationForm.companyLogoRequired'), trigger: 'change' },
    { validator: (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error(t('enterpriseCertificationForm.companyLogoRequired')))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
  companyDescription: [
    { required: true, message: t('enterpriseCertificationForm.companyDescriptionRequired'), trigger: 'blur' },
    { min: 10, max: 500, message: t('enterpriseCertificationForm.companyDescriptionLength'), trigger: 'blur' }
  ],
  mainBusiness: [
    { required: true, message: t('enterpriseCertificationForm.mainBusinessRequired'), trigger: 'change' },
    { type: 'array', min: 1, message: t('enterpriseCertificationForm.mainBusinessRequired'), trigger: 'change' }
  ],
  industry: [
    { required: true, message: t('enterpriseCertificationForm.industryRequired'), trigger: 'change' }
  ],
  companySize: [
    { required: true, message: t('enterpriseCertificationForm.companySizeRequired'), trigger: 'change' }
  ]
}))

// 选项数据
// 业务选项使用国际化
const businessOptions = computed(() => [
  { value: 'software', label: t('enterpriseCertificationForm.businessOptions.softwareDevelopment') },
  { value: 'ai', label: t('enterpriseCertificationForm.businessOptions.artificialIntelligence') },
  { value: 'ecommerce', label: t('enterpriseCertificationForm.businessOptions.ecommerce') },
  { value: 'finance', label: t('enterpriseCertificationForm.businessOptions.financialServices') },
  { value: 'education', label: t('enterpriseCertificationForm.businessOptions.educationTraining') },
  { value: 'healthcare', label: t('enterpriseCertificationForm.businessOptions.healthcare') },
  { value: 'manufacturing', label: t('enterpriseCertificationForm.businessOptions.manufacturing') },
  { value: 'trade', label: t('enterpriseCertificationForm.businessOptions.tradeImportExport') },
  { value: 'consulting', label: t('enterpriseCertificationForm.businessOptions.consultingServices') },
  { value: 'other', label: t('enterpriseCertificationForm.businessOptions.other') }
])

// 行业选项使用国际化
const industryOptions = computed(() => [
  { value: 'technology', label: t('enterpriseCertificationForm.industryOptions.technologyInternet') },
  { value: 'finance', label: t('enterpriseCertificationForm.industryOptions.financeInvestment') },
  { value: 'education', label: t('enterpriseCertificationForm.industryOptions.educationTraining') },
  { value: 'healthcare', label: t('enterpriseCertificationForm.industryOptions.healthcareHealth') },
  { value: 'manufacturing', label: t('enterpriseCertificationForm.industryOptions.manufacturing') },
  { value: 'trade', label: t('enterpriseCertificationForm.industryOptions.tradeImportExport') },
  { value: 'consulting', label: t('enterpriseCertificationForm.industryOptions.consultingService') },
  { value: 'retail', label: t('enterpriseCertificationForm.industryOptions.retailEcommerce') },
  { value: 'real_estate', label: t('enterpriseCertificationForm.industryOptions.realEstate') },
  { value: 'energy', label: t('enterpriseCertificationForm.industryOptions.energyEnvironment') },
  { value: 'media', label: t('enterpriseCertificationForm.industryOptions.mediaEntertainment') },
  { value: 'other', label: t('enterpriseCertificationForm.industryOptions.other') }
])

// 公司规模选项使用国际化
const companySizeOptions = computed(() => [
  { value: '1To10', label: t('enterpriseCertificationForm.sizeOptions.size1To10') },
  { value: '11To50', label: t('enterpriseCertificationForm.sizeOptions.size11To50') },
  { value: '51To100', label: t('enterpriseCertificationForm.sizeOptions.size51To100') },
  { value: '101To500', label: t('enterpriseCertificationForm.sizeOptions.size101To500') },
  { value: '501To1000', label: t('enterpriseCertificationForm.sizeOptions.size501To1000') },
  { value: '1000Plus', label: t('enterpriseCertificationForm.sizeOptions.size1000Plus') }
])

// 上传相关 - 禁用自动上传，在提交时一起处理
const uploadAction = '#' // 禁用自动上传
const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('access_token')}`
}

// 方法
const handleLicenseChange = (file, fileList) => {
  if (file && file.raw) {
    const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.raw.type)
    const isLt10M = file.raw.size / 1024 / 1024 < 10

    if (!isValidType) {
      ElMessage.error(t('enterpriseCertificationForm.invalidFileType'))
      return
    }
    if (!isLt10M) {
      ElMessage.error(t('enterpriseCertificationForm.fileTooLarge'))
      return
    }
    
    // 保存文件到表单数据
    certificationForm.businessLicense = [file]
    
    ElMessage.success(t('enterpriseCertificationForm.licenseSelected'))
  }
}

const handleLogoChange = (file, fileList) => {
  if (file && file.raw) {
    const isValidType = ['image/jpeg', 'image/png'].includes(file.raw.type)
    const isLt5M = file.raw.size / 1024 / 1024 < 5

    if (!isValidType) {
      ElMessage.error(t('enterpriseCertificationForm.logoInvalidFormat'))
      return
    }
    if (!isLt5M) {
      ElMessage.error(t('enterpriseCertificationForm.logoTooLarge'))
      return
    }
    
    // 保存文件到表单数据
    certificationForm.companyLogo = [file]
    
    ElMessage.success(t('enterpriseCertificationForm.logoSelected'))
  }
}

const onUploadError = (error) => {
  // 检查是否是接口未实现的错误
  if (error.message && error.message.includes('No static resource')) {
    ElMessage.error(t('enterpriseCertificationForm.uploadNotAvailable'))
  } else {
    ElMessage.error(t('enterpriseCertificationForm.uploadFailed'))
  }
}

const removeBusinessLicense = () => {
  certificationForm.businessLicense = []
  ElMessage.success(t('enterpriseCertificationForm.licenseRemoved'))
}

const removeCompanyLogo = () => {
  certificationForm.companyLogo = []
  ElMessage.success(t('enterpriseCertificationForm.logoRemoved'))
}

const submitCertification = async () => {
  try {
    const valid = await certificationFormRef.value.validate()
    
    if (!valid) {
      // 获取具体的验证错误信息
      const fields = certificationFormRef.value.fields
      const errors = []
      
      for (const field of fields) {
        if (field.validateState === 'error') {
          errors.push(field.label || field.prop)
        }
      }
      
      if (errors.length > 0) {
        ElMessage.error(`${t('enterpriseCertificationForm.checkFields')}${errors.join(', ')}`)
      } else {
        ElMessage.error(t('enterpriseCertificationForm.checkFormInfo'))
      }
      
      return
    }

    submitting.value = true

    // 检查文件是否已上传
    if (!certificationForm.businessLicense.length) {
      ElMessage.error(t('enterpriseCertificationForm.businessLicenseRequired'))
      return
    }
    
    if (!certificationForm.companyLogo.length) {
      ElMessage.error(t('enterpriseCertificationForm.companyLogoRequired'))
      return
    }

    // 获取用户ID
    const userId = localStorage.getItem('user_id')
    if (!userId) {
      ElMessage.error(t('enterpriseCertificationForm.userInfoFailed'))
      router.push('/login')
      return
    }

    // 构建certificationData JSON对象
    const certificationData = {
      enterpriseUserId: parseInt(userId),
      companyFullName: certificationForm.companyName,
      socialCreditCode: certificationForm.creditCode,
      operatorName: certificationForm.operatorName,
      operatorPosition: certificationForm.operatorPosition,
      contactPhoneNumber: certificationForm.phone,
      contactEmail: certificationForm.email || '',
      companyIntroduction: certificationForm.companyDescription,
      mainBusiness: certificationForm.mainBusiness && certificationForm.mainBusiness.length > 0 
        ? certificationForm.mainBusiness.map(business => {
            // 根据选择的值获取对应的本地化文本
            return t(`enterpriseCertificationForm.businessOptions.${business}`);
          }).join(', ') 
        : '',
      officialWebsiteUrl: certificationForm.website || '',
      industry: certificationForm.industry ? t(`enterpriseCertificationForm.industryOptions.${certificationForm.industry}`) : '',
      companyScale: certificationForm.companySize ? t(`enterpriseCertificationForm.sizeOptions.size${certificationForm.companySize}`) : '',
      companyAddress: '' // 如果需要地址字段，可以添加到表单中
    }

    // 生产模式：构建multipart/form-data请求
    const formData = new FormData()
    
    // 添加JSON数据
    const jsonBlob = new Blob([JSON.stringify(certificationData)], {
      type: 'application/json'
    })
    formData.append('certificationData', jsonBlob, 'certificationData.json')
    
    // 添加营业执照文件
    const businessLicenseFile = certificationForm.businessLicense[0]
    if (businessLicenseFile && businessLicenseFile.raw) {
      // 生成安全的文件名
      const originalName = businessLicenseFile.name
      const fileExtension = originalName.split('.').pop()
      const timestamp = Date.now()
      const safeFileName = `business_license_${timestamp}.${fileExtension}`
      
      formData.append('business_license_file', businessLicenseFile.raw, safeFileName)
    }
    
    // 添加公司Logo文件
    const companyLogoFile = certificationForm.companyLogo[0]
    if (companyLogoFile && companyLogoFile.raw) {
      // 生成安全的文件名
      const originalName = companyLogoFile.name
      const fileExtension = originalName.split('.').pop()
      const timestamp = Date.now()
      const safeFileName = `company_logo_${timestamp}.${fileExtension}`
      
      formData.append('company_logo_file', companyLogoFile.raw, safeFileName)
    }

    // 发送请求
    const response = await fetch('/api/api/v1/enterprise/certification/apply', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
      },
      body: formData
    })
    
    const result = await response.json()

    if (response.ok && result.code === 'SUCCESS') {
      ElMessage.success(result.message || '认证申请提交成功，请等待审核')
      certificationManager.clearCache()
      // 跳转到认证状态页面
      router.push({ name: 'enterprise-certification' })
    } else {
      // 处理不同的错误情况
      let errorMessage = '提交失败，请重试'
      
      switch (result.code) {
        case 'INVALID_INPUT':
          errorMessage = '关键认证信息不完整，请检查后重试'
          break
        case 'INVALID_ENTERPRISE_USER_ID':
          errorMessage = '用户信息无效，请重新登录'
          router.push('/login')
          break
        case 'SOCIAL_CREDIT_CODE_EXISTS':
          errorMessage = '该社会信用代码已被注册'
          break
        case 'DATA_INTEGRITY_VIOLATION':
          errorMessage = '数据提交失败，请检查输入内容是否符合要求'
          break
        case 'FILE_UPLOAD_ERROR':
          errorMessage = '文件上传失败，请稍后重试'
          break
        case 'INTERNAL_SERVER_ERROR':
          errorMessage = '服务器内部错误，请稍后重试'
          break
        default:
          errorMessage = result.error || result.message || '提交失败，请重试'
      }
      
      ElMessage.error(errorMessage)
    }
  } catch (error) {
    // 显示详细的错误信息
    let errorMessage = '网络错误，请稍后重试'
    
    if (error.response) {
      // 服务器返回了错误响应
      const { status, data } = error.response
      
      if (data && data.error) {
        errorMessage = data.error
      } else if (data && data.message) {
        errorMessage = data.message
      } else {
        errorMessage = `服务器错误 (${status})`
      }
    } else if (error.message) {
      // 网络错误或其他错误
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  certificationFormRef.value?.resetFields()
  certificationForm.businessLicense = []
  certificationForm.companyLogo = []
}

// 导航路由管理
const currentRoute = computed(() => {
  return route.name
})

const goBack = () => {
  ElMessageBox.confirm(
    t('enterpriseCertificationForm.confirmBackToLogin'),
    t('enterpriseCertificationForm.tip'),
    {
      confirmButtonText: t('enterpriseCertificationForm.confirm'),
      cancelButtonText: t('enterpriseCertificationForm.cancel'),
      type: 'warning'
    }
  )
  .then(() => {
    router.push('/login')
  })
  .catch(() => {
    // 用户取消操作，不做任何处理
  })
}

const navigateTo = (routeName) => {
  // 检查token是否存在
  const token = localStorage.getItem('access_token')
  if (!token) {
    ElMessage.error('登录已过期，请重新登录')
    router.push('/login')
    return
  }
  
  // 如果点击的是当前页面，不做任何操作
  if (currentRoute.value === routeName) {
    return
  }
  
  try {
    router.push({ name: routeName })
  } catch (error) {
    ElMessage.error('页面跳转失败，请重试')
  }
}

// 检查登录状态
const checkLoginStatus = () => {
  const token = localStorage.getItem('access_token')
  const userType = localStorage.getItem('user_type')
  
  if (!token) {
    ElMessage.error('登录已过期，请重新登录')
    router.push('/login')
    return false
  }
  
  if (userType !== 'enterprise') {
    ElMessage.error('权限不足')
    router.push('/')
    return false
  }
  
  return true
}

// 生命周期
onMounted(() => {
  // 检测并设置语言
  detectLanguage()
  
  // 首先检查登录状态
  if (!checkLoginStatus()) {
    return
  }
})

// 明确暴露方法给模板
defineExpose({
  removeBusinessLicense,
  removeCompanyLogo,
  navigateTo,
  resetForm,
  submitCertification,
  handleLicenseChange,
  handleLogoChange,
  onUploadError
})
</script>

<style scoped>
.certification-form-layout {
  display: flex;
  min-height: 100vh;
}

.sidebar {
  width: 250px;
  background-color: #ffffff;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 10;
  border-right: 1px solid #e0e0e0;
}

.sidebar-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  cursor: pointer;
}

.logo {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
}

.logo img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 8px;
}

.logo-text {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.sidebar-menu {
  width: 100%;
  margin-bottom: 30px;
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  width: 100%;
  user-select: none;
  position: relative;
  border-radius: 0;
}

.menu-item:hover {
  background-color: #f5f5f5;
}

.menu-item.active {
  background: #ffffff;
  color: #409EFF;
  border-radius: 0;
  border: 1px solid #409EFF;
}

.menu-item.active .menu-text,
.menu-item.active .menu-icon {
  color: #409EFF;
}

.menu-text {
  font-size: 16px;
  font-weight: 500;
  position: relative;
  z-index: 2;
  pointer-events: none;
}

.menu-icon {
  font-size: 16px;
  position: relative;
  z-index: 2;
  pointer-events: none;
  display: flex;
  flex-direction: column;
  gap: 1px;
  align-items: center;
  color: #666666;
}

.menu-item.active .menu-icon {
  color: #409EFF;
}

.menu-item:hover .menu-icon {
  color: #333333;
}

.main-content {
  flex: 1;
  margin-left: 250px; /* Adjust based on sidebar width */
  padding: 20px;
  background-color: #ffffff;
  min-height: 100vh;
}

.certification-form-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  background-color: transparent;
  border-radius: 0;
  box-shadow: none;
}

.form-header {
  text-align: left;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #EBEEF5;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.page-subtitle {
  font-size: 16px;
  color: #606266;
}

.certification-form-card {
  margin-bottom: 30px;
  border: 1px solid #e0e0e0;
  border-radius: 0;
  box-shadow: none;
}

.certification-form {
  margin-top: 20px;
}

.form-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

/* 统一的上传组件样式 */
.upload-container {
  width: 100%;
}

.upload-component {
  width: 100%;
}

.upload-component :deep(.el-upload) {
  width: 100%;
  display: block;
}

.upload-area {
  width: 100%;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 20px;
}

.upload-area:hover {
  border-color: #409EFF;
  background-color: #f0f9ff;
}

.upload-text {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-top: 8px;
  margin-bottom: 4px;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
  text-align: center;
  line-height: 1.4;
}

/* 上传预览样式 */
.upload-preview {
  width: 100%;
  height: 120px;
  border: 2px solid #67C23A;
  border-radius: 8px;
  background-color: #f0f9ff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  padding: 20px;
}

.preview-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
}

.preview-text {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-top: 8px;
  margin-bottom: 4px;
  text-align: center;
  word-break: break-all;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.preview-hint {
  font-size: 12px;
  color: #67C23A;
  text-align: center;
  line-height: 1.4;
}

.remove-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  font-size: 12px;
  padding: 4px 8px;
}

.form-row {
  display: flex;
  gap: 30px;
  margin-bottom: 20px;
}

.form-column {
  flex: 1;
}

.form-column :deep(.el-form-item) {
  margin-bottom: 20px;
}

.form-column :deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

.form-column :deep(.el-input__wrapper) {
  border-radius: 4px;
}

.form-column :deep(.el-select) {
  width: 100%;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
}

.form-actions .el-button {
  margin: 0 10px;
}



:deep(.el-form-item__label) {
  font-weight: 500;
}

.form-actions .el-button {
  padding: 12px 24px;
  font-size: 16px;
}
</style> 